package org.dromara.knowledgebase.service;

import cn.hutool.core.util.IdUtil;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.knowledgebase.core.page.PageQuery;
import org.dromara.knowledgebase.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.knowledgebase.domain.Knowledge;
import org.dromara.knowledgebase.domain.bo.KnowledgeBo;
import org.dromara.knowledgebase.repository.KnowledgeRepository;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.UpdateResponse;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Optional;

@RequiredArgsConstructor
@Service
public class KnowledgeService {

    private final KnowledgeRepository knowledgeRepository;

    private final ElasticsearchOperations elasticsearchOperations;

    public TableDataInfo<Knowledge> selectPageKnowledgeList(KnowledgeBo knowledgeBo, PageQuery pageQuery) {

        if (StringUtils.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("createTime");
            pageQuery.setIsAsc("desc");
        }

        Criteria criteria = new Criteria();


        CriteriaQuery query = new CriteriaQuery(criteria,pageQuery.build());

        //通过用户ID路由
        query.setRoute(LoginHelper.getUserIdStr());


        SearchHits<Knowledge> searchHits = elasticsearchOperations.search(query,Knowledge.class);

        return TableDataInfo.build(searchHits);
    }

    public Optional<Knowledge> queryById(@NonNull Long id) {
        return knowledgeRepository.findById(id);
    }

    public Knowledge insertByBo(@NonNull KnowledgeBo bo) {
        Knowledge knowledge = MapstructUtils.convert(bo, Knowledge.class);
        knowledge.setDocumentId(IdUtil.getSnowflakeNextIdStr());
        return knowledgeRepository.save(knowledge);
    }

    public void deleteById(@NonNull Long knowledgeId) {
        knowledgeRepository.deleteById(knowledgeId);
    }

    public void deleteByIds(@NonNull Collection<Long> ids) {
        knowledgeRepository.deleteAllById(ids);
    }

    public UpdateResponse.Result updateByBo(@NonNull KnowledgeBo bo) {

        Knowledge knowledge = MapstructUtils.convert(bo, Knowledge.class);
        return elasticsearchOperations.update(knowledge).getResult();
    }
}
